<template>
  <uni-popup
    ref="popup"
    :mask-click="false"
    :length="'50%'"
    @close="reset"
  >
    <view class="popup-wrapper">
      <!-- 标题栏 -->
      <view class="popup-header-box">
        <view class="popup-header-left">
          <text
            class="btn-cancel"
            @click="cancelClick"
          >取消</text>
        </view>
        <view class="popup-header-center">人员选择</view>
        <view class="popup-header-right">
          <text
            class="btn-confirm"
            :class="{ 'hide-confirm': props.singleSelect }"
            @click="confirmClick"
          >确定</text>
        </view>
      </view>

      <!-- 搜索区域 -->
      <view class="search-wrapper">
        <up-input
          v-model="info.spell"
          placeholder="请输入"
          clearable
          @change="filterContent"
          class="h-full"
        ></up-input>
      </view>

      <!-- 人员展示区域 -->
      <view class="content-wrapper">
        <scroll-view
          class="content-scroll"
          :scroll-y="true"
          @scrolltolower="loadMore"
          @scrolltoupper="refreshContent"
        >
          <view class="content-box">
            <view
              class="list-item"
              v-for="item in info.list"
              :key="item.value"
              @click="selectItem(item)"
            >
              <uni-icons
                v-if="!isSelected(item)"
                type="circle"
                size="30"
              ></uni-icons>
              <uni-icons
                v-else
                type="checkbox-filled"
                size="30"
                color="#007aff"
              ></uni-icons>

              <text
                class="list-text"
                :class="{
                  active: isSelected(item),
                }"
              >{{ item.showname }}</text>
            </view>
            <uni-load-more :status="info.loadStatus" />
          </view>
        </scroll-view>
      </view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref, computed, reactive, watch, getCurrentInstance } from 'vue';
import utils from '@/common/js/utils/index.js';
import { getPerson } from '@/api';

const emit = defineEmits(['personSelected']);
const popup = ref(null);

const props = defineProps({
  // 是单选 还是多选
  singleSelect: {
    type: Boolean,
    default: true,
  },
  // 默认选中人员
  defaultSelected: {
    type: Array,
    default: () => [],
  },
  defaultName: {
    type: Array,
    default: () => [],
  },
});

const info = reactive({
  spell: '', // 搜索框的输入内容
  loadStatus: 'noMore', // more、loading、noMore
  list: [
    // {
    //   showname: '梁淮君，光学制造部',
    //   deptseq: '1607908252521',
    //   name: '梁淮君',
    //   value: '800180',
    //   deptname: '光学制造部',
    // },
    // {
    //   showname: '唐常圆，工程技术部',
    //   deptseq: '1614828528163',
    //   name: '唐常圆',
    //   value: '800183',
    //   deptname: '工程技术部',
    // },
  ],
  selectedValueArr: [...props.defaultSelected], // 选中的人员id组合
  selectedNameArr: [...props.defaultName], // 选中的人员id组合
});

const forceUpdate = () => {
  const instance = getCurrentInstance();
  if (instance && instance.proxy) {
    instance.proxy.$forceUpdate(); // 强制更新
  }
};

// 请求人员
const fetchData = () => {
  // 请求数据并更新 persons
  getPerson({
    spell: info.spell || '',
    number: 500,
  })
    .then((res) => {
      console.log('获取人员res', res);
      info.list = res || [];
      forceUpdate();
      // info.turnInfo.count = res.count || 0;
      // if (info.query.page === 1) {
      //   info.list = res.data;
      // } else {
      //   info.list = [...info.list, ...res.data];
      // }
      // if (info.list.length < info.turnInfo.count) {
      //   info.loadStatus = 'more';
      //   info.page++;
      // } else {
      //   info.loadStatus = 'noMore';
      // }
    })
    .catch((error) => {
      console.log('获取人员 error', error);
    });
};

// 左上角取消按钮事件
const cancelClick = () => {
  popup.value.close();
};

// 右上角确定按钮事件
const confirmClick = () => {
  console.log(157, '确定事件selectedNameArr', info.selectedNameArr);
  console.log(158, 'selectedValueArr', info.selectedValueArr);
  emit('personSelected', info.selectedValueArr, info.selectedNameArr);
  popup.value.close();
};

// 顶部的搜索
const filterContent = utils.debounce((val) => {
  console.log('输入的内容为：', val);
  info.spell = val;
  fetchData();
}, 300);

// 加载更多
const loadMore = () => {
  console.log('加载更多');
};

// 刷新内容
const refreshContent = () => {
  console.log('刷新内容');
};

// 选择子项
const selectItem = (item, name) => {
  if (props.singleSelect) {
    info.selectedNameArr = [item.name];
    info.selectedValueArr = [item.value];
    confirmClick(); // 调用确定事件
  } else {
    if (isSelected(item)) {
      const findIndex = info.selectedValueArr.findIndex(
        (v) => v === item.value
      );
      info.selectedValueArr.splice(findIndex, 1);
      info.selectedNameArr.splice(findIndex, 1);
    } else {
      info.selectedNameArr.push(item.name);
      info.selectedValueArr.push(item.value);
    }
  }
  console.log('选择的人员', info.selectedNameArr);
  console.log('选择的人员', info.selectedValueArr);
};

// 是否是选中人员
const isSelected = (item) => {
  return info.selectedValueArr.includes(item.value);
};

// 关闭弹窗时重置
const reset = () => {
  info.spell = '';
};

// 打开弹窗
const open = () => {
  reset();
  fetchData();
  info.selectedValueArr = [...props.defaultSelected];
  info.selectedNameArr = [...props.defaultName];
  popup.value.open('bottom');
};

onMounted(() => {
  // fetchData(); // 获取人员
  console.log('props.singleSelect', props.singleSelect);
  console.log('props.defaultSelected', props.defaultSelected);
  console.log('props.defaultName', props.defaultName);

});
// 使用 defineExpose 暴露方法给父组件调用
defineExpose({
  open,
  reset,
});
</script>

<style lang="scss" scoped>
.popup-wrapper {
  position: relative;
  z-index: 2;
  width: 100%;
  height: 60vh;
  background-color: #fff;
  border-top-right-radius: 8rpx;
  border-top-left-radius: 8rpx;
}

.popup-header-box {
  display: flex;
  height: 40px;
  padding: 0 10rpx;
  align-items: center;

  .popup-header-left {
    .btn-cancel {
      display: inline-flex;
      padding: 6px;
      color: #999;
      font-size: 22px;
    }
  }

  .popup-header-center {
    width: 60%;
    flex: 1;
    text-align: center;
    font-size: 22px;
    font-weight: bold;
  }

  .popup-header-right {
    .btn-confirm {
      display: inline-flex;
      padding: 6px;
      color: #333;
      font-size: 20px;

      &.hide-confirm {
        visibility: hidden;
        pointer-events: none;
      }
    }
  }
}

.search-wrapper {
  margin-top: 10px;
  padding: 0 12px;
  height: 34px;
}

.content-wrapper {
  position: absolute;
  width: 100%;
  bottom: 0;
  z-index: 3;
  height: calc(100% - 40px - 34px - 10px - 10px);
  padding: 0 12rpx;

  .content-scroll {
    height: 100%;
    min-height: 100%;

    .content-box {
      height: 100%;
      min-height: 100%;
    }
  }
}

.list-item {
  display: flex;
  align-items: center;
  padding: 10rpx 0;
  border-top: 1rpx solid #e5e5e5;

  .list-radio {}

  .list-checkbox {}

  .list-text {
    flex: 1;
    padding-left: 4rpx;

    &.active {
      color: #007aff;
    }
  }
}
</style>
